package controllers

import (
	"gin-meilisearch-student/config"
	"gin-meilisearch-student/models"
	"github.com/gin-gonic/gin"
	"github.com/meilisearch/meilisearch-go"
	"net/http"
	"strconv"
)

var meilisearchClient meilisearch.ServiceManager

func init() {
	config.InitMeilisearch()

	meilisearchClient = *config.MeilisearchClient

}
func AddStudent(c *gin.Context) {
	var student models.Student

	if err := c.ShouldBindJSON(&student); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	// 使用 Meilisearch 添加文档
	_, err := meilisearchClient.Index(models.IndexName).AddDocuments([]interface{}{student})
	if err != nil {

	}

}

func GetStudent(c *gin.Context) {
	id := c.Param("id")

	res, err := meilisearchClient.Index(models.IndexName).Search("", &meilisearch.SearchRequest{
		Filter: "id = " + id,
		Limit:  1,
	})

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	if len(res.Hits) == 0 {
		c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
		return
	}
	c.JSON(http.StatusOK, res.Hits[0])
}

// GetAllStudents 获取所有学生
func GetAllStudents(c *gin.Context) {
	// 获取查询参数
	query := c.DefaultQuery("q", "")
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", "10"))
	offset, _ := strconv.Atoi(c.DefaultQuery("offset", "0"))

	// 使用 Meilisearch 搜索
	res, err := meilisearchClient.Index(models.IndexName).Search(query, &meilisearch.SearchRequest{
		Limit:  int64(limit),
		Offset: int64(offset),
	})
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"total": res.EstimatedTotalHits, "students": res.Hits})
}

// UpdateStudent 更新学生信息
func UpdateStudent(c *gin.Context) {

	id := c.Param("id")
	var student models.Student
	if err := c.ShouldBindJSON(&student); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	//确保ID一致
	student.ID = id

	// 使用 Meilisearch 更新文档
	_, err := meilisearchClient.Index(models.IndexName).UpdateDocuments([]models.Student{student})
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "student updated", "student": student})

}

// DeleteStudent 删除学生

func DeleteStudent(c *gin.Context) {
	id := c.Param("id")
	_, err := meilisearchClient.Index(models.IndexName).DeleteDocument(id)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "student deleted", "student": id})
}
